package com.lixianhe.onlineexam.controller;

import com.lixianhe.onlineexam.pojo.Student;
import com.lixianhe.onlineexam.service.StudentService;
import com.lixianhe.onlineexam.util.ApiResultHandler;
import com.lixianhe.onlineexam.util.PageBean;
import com.lixianhe.onlineexam.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/students/{page}/{size}")
    public R students(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageBean<Student> studentPageInfo = studentService.selectStudentByPage(page, size);
        return ApiResultHandler.buildApiResult(200, "所有学生", studentPageInfo);
    }

    @GetMapping("/student/{id}")
    public R student(@PathVariable Integer id) {
        Student student = studentService.selectStudentById(id);
        return ApiResultHandler.buildApiResult(200, "查找学生", student);
    }

    @PutMapping("/student")
    public R updaetStudent(@RequestBody Student student) {
        int e = studentService.updateStudent(student);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "更新成功", e);
        return ApiResultHandler.buildApiResult(400, "更新失败", e);
    }

    @PostMapping("/student")
    public R addStudent(@RequestBody Student student) {
        int e = studentService.addStudent(student);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "添加成功", e);
        return ApiResultHandler.buildApiResult(400, "添加失败", e);
    }

    @DeleteMapping("/student/{id}")
    public R deleteStudent(@PathVariable("id") Integer id) {
        int e = studentService.deleteStudent(id);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "删除成功", e);
        return ApiResultHandler.buildApiResult(400, "删除失败", e);
    }

    @PutMapping("studentPWD")
    public R updateStudentPwd(@RequestBody Student student) {
        System.out.println("student....");
        int e = studentService.updateStudentPwd(student);
        if (e == 1) return ApiResultHandler.buildApiResult(200, "修改密码成功", e);
        return ApiResultHandler.buildApiResult(400, "修改密码失败", e);

    }

    @PostMapping("/studentExit")
    public R exit(HttpServletRequest request) {
        request.getSession().removeAttribute("student");
        return ApiResultHandler.buildApiResult(200, "退出成功", null);
    }

}
